package com.xindaoapp.happypet.activity;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.MyShopCollectAdapter;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.ShopCollect;
import com.xindaoapp.happypet.bean.ShopCollectEntity;
import com.xindaoapp.happypet.bean.ShopCollectList;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.xdConfig;

/**
 * 商城我的收藏列表
 * 
 * @author Administrator
 */
public class MyShopCollectActivity extends BaseLoadAnimationAcitivity implements OnClickListener {
    private final static String TAG = "MyShopCollectActivity";

    private Activity mContext;
    private ImageButton back;
    private PullToRefreshListView listView;
    private MyShopCollectAdapter adapter;

    private MyShopCollectBroadCast broadCast;
    private int location;

    // private TextView tittle_edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_myshop_collect);
        super.onCreate(savedInstanceState);
        mContext = MyShopCollectActivity.this;

        initView();
        initData();

        initMyData();
        refreshAndLoadMore();

        broadCast = new MyShopCollectBroadCast();
        registerReceiver(broadCast, new IntentFilter(Constants.SHOP_COLLECT));
    }

    private void initView() {
        back = (ImageButton) findViewById(R.id.cancel);

        listView = (PullToRefreshListView) findViewById(R.id.myshop_listview);
        listView.setOnItemClickListener(mOnItemClickListener);
        listView.getRefreshableView().setOnItemLongClickListener(mOnItemLongClickListener);
        // tittle_edit = (TextView) findViewById(R.id.tittle_edit);
        // tittle_edit.setOnClickListener(this);
    }

    private final OnItemLongClickListener mOnItemLongClickListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position,
                long id) {
            new AlertDialog.Builder(MyShopCollectActivity.this).setTitle("删除")
                    .setMessage("确定要删除吗?")
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (UserState.isLogged(mContext)) {
                                location = position - 1;
                                getDelCollectData(((ShopCollect) parent.getItemAtPosition(position)).goods_id);
                            }
                            dialog.dismiss();
                        }
                    }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                    }).create().show();

            return false;
        }

    };

    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(mContext, ProductDetailActivity1.class);
            intent.putExtra("productId",
                    ((ShopCollect) parent.getItemAtPosition(position)).goods_id);
            location = position - 1;
            startActivity(intent);
        }
    };

    private void refreshAndLoadMore() {
        listView.setMode(Mode.PULL_FROM_START);
        listView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                initMyData();
            }
        });
    }

    private boolean isFirst = true;

    private void initMyData() {
        getData(mContext, 1, xdConfig.PAGE_SIZE, new ILoadNextPageData<ShopCollect>() {

            @Override
            public void loadNextPageData(List<ShopCollect> t) {
                if (null != t) {
                    isFirst = false;
                    onDataArrived(true);
                    adapter =
                            new MyShopCollectAdapter(mContext, t, xdConfig.PAGE_SIZE,
                                    R.layout.activity_myshop_collect_item, R.layout.item_loading);
                    if (adapter.getResult().size() > 0) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    } else {
                        loading.setVisibility(View.VISIBLE);
                        animation.stop();
                        imageView.setVisibility(View.GONE);
                        load_fail.setVisibility(View.VISIBLE);
                    }
                    listView.setAdapter(adapter);
                    listView.setPullLabel("加载成功");
                } else {
                    if (isFirst) {
                        onDataArrived(false);
                        SetOnLoadFailListener(new OnLoadFailListener() {
                            @Override
                            public void onLoadFail() {
                                initMyData();
                            }
                        });
                    } else {
                        onDataArrived(true);
                    }
                }
                listView.onRefreshComplete();
            }
        });
    }

    public static void getData(final Context mContext, int pageNumber, int size,
            final ILoadNextPageData<ShopCollect> iRequest) {
        // if (CommonUtil.checkNetState(mContext)) {
        RequestParams params = new RequestParams();
        params.put("userID", UserState.getUserUid());
        params.put("page", String.valueOf(pageNumber));
        params.put("pageSize", String.valueOf(size));

        // final ProgressHUD progressHUD = ProgressHUD.show(mContext, "正在加载...", true, true, null);
        AddClient.get(Address.SHOP_COLLECTION, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                /*
                 * if (null != progressHUD && progressHUD.isShowing()) { progressHUD.dismiss(); }
                 */
                ShopCollectEntity entity = null;

                try {
                    entity = JSON.parseObject(content, ShopCollectEntity.class);
                } catch (Exception e) {
                }
                if (null == entity) {
                    Toast.makeText(mContext, R.string.get_error_data, 0).show();
                    return;
                }

                String data = entity.data;

                ShopCollectList obj = null;

                try {
                    obj = JSON.parseObject(data, ShopCollectList.class);
                } catch (Exception e) {
                }

                // 判断返回数据是否正确
                if (null != obj) {
                    iRequest.loadNextPageData(obj.info);
                } else {
                    iRequest.loadNextPageData(null);
                }
            }

            @Override
            public void onFailure(Throwable arg0, String arg1) {
                /*
                 * if (null != progressHUD && progressHUD.isShowing()) { progressHUD.dismiss(); }
                 */
                super.onFailure(arg0, arg1);
                iRequest.loadNextPageData(null);
            }
        });
    }

    private void initData() {
        back.setOnClickListener(this);
    }

    private void getDelCollectData(String goodsID) {
        final RequestParams params = new RequestParams();
        params.put("userID", UserState.getUserUid());
        params.put("goodsID", goodsID);
        AddClient.get(Address.DEL_COLLECTION, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                int result = -1;
                JSONObject obj;
                try {
                    obj = new JSONObject(content);
                    result = obj.getInt("status");
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                if (result == 1) {// 说明没有赞
                    Toast.makeText(mContext, "取消收藏成功", Toast.LENGTH_SHORT).show();
                    adapter.getResult().remove(location);
                    adapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(mContext, "取消收藏失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Throwable arg0, String arg1) {
                super.onFailure(arg0, arg1);
                Toast.makeText(mContext, R.string.get_error_data, 0).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(broadCast);
    }

    class MyShopCollectBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            adapter.getResult().remove(location);
            adapter.notifyDataSetChanged();

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                finish();
                break;
        // 编辑收藏的按钮
        // case R.id.tittle_edit:
        // if(tittle_edit.getText().toString().equals("编辑")){
        // adapter.setEditMode(true);
        // tittle_edit.setText("删除");
        // adapter.notifyDataSetChanged();
        // }else if(tittle_edit.getText().toString().equals("删除")){
        // //删除收藏的商品
        // deleteShopCollectProduct();
        //
        // }
        // break;
        }

    }

    /** 删除收藏商品 */
    private void deleteShopCollectProduct() {
        new AlertDialog.Builder(getApplicationContext()).setTitle("确认").setMessage("是否确定删除？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 未完成，已有长按删除功能
                        Toast.makeText(getApplicationContext(), "执行删除的操作", 1).show();
                        closeEditMode();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        closeEditMode();
                    }
                }).create().show();
    }

    private void closeEditMode() {
        // tittle_edit.setText("编辑");
        // adapter.setEditMode(false);
        adapter.notifyDataSetChanged();
    }



}
